1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| #include <iostream> #include <opencv2/opencv.hpp>
using namespace cv; using namespace std;
int main(){ Mat img, img_gray,hist; img = imread("/home/v/home.png"); if (img.empty()){ cout << "Could not open or find the image" << endl; return -1; }
cvtColor(img, img_gray, COLOR_BGR2GRAY); imshow("img gray",img_gray);
int histSize = 256; float range[] = { 0, 256 }; const float* histRange = { range }; calcHist(&img_gray, 1, 0, Mat(), hist, 1, &histSize, &histRange, true, false);
int hist_h = 300; int hist_w = 512; int bin_w = hist_w / histSize; Mat hist_img(hist_h, hist_w, CV_8UC3, Scalar(0, 0, 0));
normalize(hist, hist, 0, hist_h, NORM_MINMAX, -1, Mat()); for (int i=1;i<histSize;i++){ line(hist_img, Point(bin_w*(i-1), hist_h - cvRound(hist.at<float>(i-1))), Point(bin_w*(i), hist_h - cvRound(hist.at<float>(i))), Scalar(0, 0, 255), 2, 8, 0); }
imshow("直方图",hist_img); waitKey(0); return 0; }
|